<template>
  <el-card class="filter-card" :body-style="{ padding: '15px' }">
    <DynamicForm
      ref="formRef"
      v-model="formData"
      :form-config="formConfig"
      :gutter="16"
      type="search"
      @search="handleSearch"
      @reset="handleReset"
    />
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";

// 定义属性和事件
const props = defineProps({
  formData: {
    type: Object,
    default: () => ({
      name: "",
      status: "",
      keyword: "",
    }),
  },
});

const emit = defineEmits(["search", "reset"]);

const formRef = ref<DynamicFormInstance>();

// 表单数据
const formData = reactive({
  name: props.formData.name || "",
  status: props.formData.status || "",
  keyword: props.formData.keyword || "",
});

// 监听父组件表单数据变化
watch(
  () => props.formData,
  (newVal) => {
    formData.name = newVal.name || "";
    formData.status = newVal.status || "";
    formData.keyword = newVal.keyword || "";
  },
  { deep: true }
);

// 表单配置
const formConfig: FormItemConfig[] = [
  {
    key: "name",
    name: "模板名称",
    type: "input",
    placeholder: "输入模板名称",
    params: {
      clearable: true,
    },
    col: { span: 4 },
  },
  {
    key: "status",
    name: "启用状态",
    type: "select",
    placeholder: "选择状态",
    params: {
      clearable: true,
    },
    options: [
      { label: "启用", value: "启用" },
      { label: "禁用", value: "禁用" },
    ],
    col: { span: 4 },
  },
  {
    key: "keyword",
    name: "搜索",
    type: "input",
    placeholder: "输入关键词",
    params: {
      clearable: true,
    },
    col: { span: 4 },
  },
];

// 方法 - 搜索
const handleSearch = (data: any) => {
  emit("search", data);
};

// 方法 - 重置
const handleReset = () => {
  formData.name = "";
  formData.status = "";
  formData.keyword = "";
  emit("reset");
};
</script>

<style scoped lang="scss">
.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

::v-deep .el-form-item {
  margin-bottom: 10px;
}
</style>
